package com.tys.algorithm.beginner;

// 测试链接：https://leetcode.com/problems/divide-two-integers
public class Code18_BitAddMinusMultiDiv {

    //加法
    public static int add(int a, int b) {
        int sum = a;
        while (b != 0) {
            sum = a ^ b;
            b = (a & b) << 1;
            a = sum;
        }
        return sum;
    }

    //正数转负数
    public static int negNum(int n) {
        return add(~n, 1);
    }

    //减法
    public static int minus(int a, int b) {
        return add(a, negNum(b));
    }

    //乘法
    public static int multi(int a, int b) {
        int res = 0;
        while (b != 0) {
            if ((b & 1) != 0) {
                res = add(res, a);
            }
            a <<= 1;
            b >>>= 1;
        }
        return res;
    }

    //判断是否是负数
    public static boolean isNeg(int n) {
        return n < 0;
    }

    //除法
    public static int div(int a, int b) {
        //转为正数
        int x = isNeg(a) ? negNum(a) : a;
        int y = isNeg(b) ? negNum(b) : b;
        int res = 0;

        for (int i = 30; i >= 0; i = minus(i, 1)) {
            if ((x >> i) >= y) {
                res |= (1 << i);
                x = minus(x, y << i);
            }
        }
        return isNeg(a) ^ isNeg(b) ? negNum(res) : res;
    }

    //系统最小的情况处理
    public static int divide(int a, int b) {

        if (a == Integer.MIN_VALUE && b == Integer.MIN_VALUE) { //a和b都是系统最小值
            return 1;
        } else if (b == Integer.MIN_VALUE) { //b是系统最小
            return 0;
        } else if (a == Integer.MIN_VALUE) { //a是系统最小
            if (b == negNum(1)) { //b是-1时，leedcode约定返回系统最大
                return Integer.MAX_VALUE;
            } else { //一般情况
                int c = div(add(a, 1), b);
                return add(c, div(minus(a, multi(c, b)), b));
            }
        } else { //a和b都不是系统最小
            return div(a, b);
        }
    }


    public static void main(String[] args) {
        System.out.println(add(1, 33));
        System.out.println(minus(44, 33));
        System.out.println(multi(3, 7));
        System.out.println(Integer.MIN_VALUE);
        System.out.println(-Integer.MIN_VALUE);

        System.out.println(divide(Integer.MIN_VALUE, Integer.MIN_VALUE));
        System.out.println(divide(8, Integer.MIN_VALUE));
        System.out.println(divide(Integer.MIN_VALUE, -1));
        System.out.println(divide(Integer.MIN_VALUE, 8));
        System.out.println(divide(8, 2));
    }
}
